package com.softmarket.action.manager;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.seasar.framework.log.Logger;
import org.seasar.struts.annotation.Execute;

import com.softmarket.action.BaseAction;
import com.softmarket.dto.DownloadPasswordDto;
import com.softmarket.dto.RakutenOrderInfoDto;
import com.softmarket.exception.RakutenException;
import com.softmarket.login.RakutenLoginRmsOrder;
import com.softmarket.service.DownloadPasswordService;
import com.softmarket.service.RakutenShippingService;

public class DownloadYamatoCsvAction extends BaseAction {
	static Logger logger = Logger.getLogger(DownloadYamatoCsvAction.class);

	public String u64;
	public String u32;
	public String p64;
	public String p32;

	private String shop_id = "298229";

	public SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

	@Execute(validator = false)
	public String index() {
		return "../downloadYamatoCsv.jsp";
	}

	@Execute(validator = false)
	public String doGetCsv() throws IOException, RakutenException {
		String returnMessage = "";
		new RakutenLoginRmsOrder().doLogin(shop_id);
		RakutenShippingService service = new RakutenShippingService();
		List<RakutenOrderInfoDto> resultList = new ArrayList<RakutenOrderInfoDto>();
		if (u64 != null && !u64.equals("")) {
			resultList.addAll(service.getOrderList(shop_id, u64));
		}

		if (u32 != null && !u32.equals("")) {
			resultList.addAll(service.getOrderList(shop_id, u32));
		}

		if (p64 != null && !p64.equals("")) {
			resultList.addAll(service.getOrderList(shop_id, p64));
		}

		if (p32 != null && !p32.equals("")) {
			resultList.addAll(service.getOrderList(shop_id, p32));
		}

		String fileName = sdf.format(new Date()) + ".csv";
		// response.getWriter().write(returnMessage);
		response.setContentType("application/octet-stream;charset=euc-jp");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		PrintWriter out = response.getWriter();

		try {

			for (RakutenOrderInfoDto current : resultList) {
				String orderNumber = current.getOrderNumber();
				String[] customerInfo = current.getShippingInfo().get(0).get(0)
						.split("<br>");
				String customerName = customerInfo[0];
				String postNumber = customerInfo[1];
				String customerAddress = customerInfo[2];
				String customerTel = customerInfo[3];

				System.out.println(orderNumber + "," + customerName + "," + postNumber
						+ "," + customerAddress + "," + customerTel);
				out.print(orderNumber + "," + customerName + "," + postNumber
						+ "," + customerAddress + "," + customerTel);
				out.print("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			out.close();
		}

		return null;
	}

}
